<?php

    /**
     * @package      Modules
     * @subpackage   Page_Classes_Db
     *
     * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
     */
    class DbPage extends BaseDbPage
    {

    ////////////////////////////////////////////////////////////////////////////
	//                               Attributes                               //
	////////////////////////////////////////////////////////////////////////////

        /**
         * Pages cache
         * 
         * @var     Collection<DbPage>
         */
        private static $_cache = null;

    ////////////////////////////////////////////////////////////////////////////
	//                                Public methods                          //
	////////////////////////////////////////////////////////////////////////////


        /**
         * preSave override
         *
         * @param Doctrine_Event $event
         */
        public function preSave($event)
        {
            if ($this->title === null || $this->title === '' ) {
                $this->title = $this->name;
            }
        }

        /**
         *
         * @param   string  $url
         */
        public static function match($url)
        {
            $pages = Doctrine_Query::create()
                        ->from(__CLASS__ .' page')
                        ->where('page.status = ?', DbBase::ENABLED)
                        ->addWhere('page.external = ?', false)
                        ->execute();

            $matches = array();

            if (strpos($url, ' ') !== false) {
                $url = str_replace(' ', '+', $url);
            }

            $url = str_replace('?<__', '?<', $url);
            $url = str_replace('__>', '>', $url);

            foreach ($pages as $page) {
                $matches = array();

                if (preg_match('/^'. str_replace('/', '\/', $page->url) .'[\/]?$/', $url, $matches) > 0) {
                    return array(
                        'page'      => $page,
                        'params'    => $matches
                    );
                }
            }
        }

        /**
         * Gets URL from page slug with parameters
         *
         * @param       string      $pageSlug
         * @param       array       $params
         * @param       string      $protocol
         * @return      string
         */
        public static function getUrl($pageSlug, array $params = array(), $protocol = 'http')
        {
            if (self::$_cache === null) {
                self::$_cache = Doctrine_Query::create()
                                    ->from(__CLASS__ .' p INDEXBY p.slug')
                                    ->where('p.status = ?', DbBase::ENABLED)
                                    ->execute();
            }

            $page = self::$_cache[$pageSlug];

            if (!$page) {
                return '';
            }

            if ($page->external) {
                return $page->url;
            }
            
            $subdomain = null;

            // Replace params by their key
            $url = stripslashes($page->url);

            /*
             * Subdomain
             */
            $http_host = explode('.', $_SERVER['HTTP_HOST']);
            $localhost_or_ip = ((count($http_host) == 1) || (count($http_host) == 4));

            if (preg_match('/\(\?<__(.*)__>[^)]*\)\??/', $url)) {
                foreach ($params as $key => $value) {
                    $matches = array();

                    if (preg_match('/\(\?<__('. $key .')__>[^)]*\)\??/', $url, $matches) > 0) {
                        if (!$localhost_or_ip) {
                            $url        = preg_replace('/\(\?<__'. $key .'__>[^)]*\)\??/', '', $url);
                            $subdomain  = $value;
                        } else {
                            $url = preg_replace('/\(\?<__'. $key .'__>[^)]*\)\??/', $value, $url);
                        }

                        break;
                    }
                }

                if ($subdomain === null) {
                    $matches = array();

                    if (preg_match('/\(\?<__(.*)__>[^)]*\)\??/', $url, $matches) > 0) {
                        if (!$localhost_or_ip) {
                            $url        = preg_replace('/\(\?<__(.*)__>[^)]*\)\??/', '', $url);
                            $subdomain  = $matches[1];
                        } else {
                            $url = preg_replace('/\(\?<__(.*)__>[^)]*\)\??/', $matches[1], $url);
                        }
                    }
                }
            }

            if ($subdomain === null) {
                $subdomain = 'www';
            }

            $registry   = Zend_Registry::getInstance();
            $webroot    = Core_Url::getDomain($subdomain .'.') . $registry['config']->urlengine->basePath;

            foreach ($params as $key => $value) {
                $url = preg_replace('/(\(\?<'. $key .'>[^)]*\)\??)/', $value, $url);
            }

            $url = preg_replace('/(\(\?<.+>[^)]*\)\??)/', '', $url);
            $url = str_replace('?', '', $url);

            if (!in_array(Core_IO_Path::getExtension($url), array('.htm', '.html'))) {
                if (substr($url, -1, 1) != '/') {
                    $url .= '/';
                }
            }

            /*
             * Cleans URL
             */
            $url = str_replace('/.', '.', $url);
            $url = preg_replace('/([\/]+)/', '/', $webroot . $url);

            return $protocol .'://'. $url;
        }

        public static function findBySlug($slug) {
            return Doctrine_Query::create()
                        ->from(__CLASS__ .' page')
                        ->where('page.status = ?', DbBase::ENABLED)
                        ->addWhere('page.slug = ?', $slug)
                        ->fetchOne();
        }

        /**
         * __toString override
         *
         * @return  string
         */
        public function __toString()
        {
            return $this->slug;
        }
    }